package com.heima.article.job;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.mess.app.AggBehaviorDTO;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@Slf4j
public class UpdateHotArticleJob {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    HotArticleService hotArticleService;

    @XxlJob("updateHotArticleJob")
    public ReturnT updateHotArticleHandler(String params) {
        log.info("热文章分值更新 调度任务开始执行....");
        // TODO 定时更新文章热度
        // 1. 获取redis 行为列表中待处理数据
        List<NewBehaviorDTO> articleMessList = getRedisBehaviorList();
        //判断集合是否为空
        if (CollectionUtils.isNotEmpty(articleMessList)) {
            log.info(" 太冷清了，文章 没有任何人访问~ ");
            return ReturnT.SUCCESS;
        }
        // 2. 将数据按照文章分组  进行聚合统计 得到待更新的数据列表
        List<AggBehaviorDTO> aggBehaviorDTOS = getAggBehaviorList(articleMessList);

        //判断集合是否为空
        if (CollectionUtils.isNotEmpty(aggBehaviorDTOS)) {
            log.info(" 太冷清了，文章没有任何人访问~ ");
            return ReturnT.SUCCESS;
        }

        // 3. TODO 更新数据库文章分值
        aggBehaviorDTOS.forEach(hotArticleService::updateApArticle);
        log.info("热文章分值更新 调度任务完成....");
        return ReturnT.SUCCESS;
    }

    /**
     * 按文章分组  每个文章的所有行为 进行聚合处理
     * @param behaviorist 处理结果集合
     * @return
     */
    private List<AggBehaviorDTO> getAggBehaviorList(List<NewBehaviorDTO> behaviorist) {
        // 1. 按照文章id对行为进行分组
        List<AggBehaviorDTO> aggBehaviorDTOList = new ArrayList<>();
        Map<Long, List<NewBehaviorDTO>> map = behaviorist.stream()
                        .collect(Collectors.groupingBy(NewBehaviorDTO::getArticleId));

        //遍历map集合
        map.forEach((articleId,behaviorDTOList)->{
            Optional<AggBehaviorDTO> reduce = behaviorDTOList.stream().map(behavior -> {
                AggBehaviorDTO dto = new AggBehaviorDTO();
                dto.setArticleId(articleId);
                switch (behavior.getType()) {
                    case LIKES:
                        dto.setLike(behavior.getAdd());
                        break;
                    case VIEWS:
                        dto.setView(behavior.getAdd());
                        break;
                    case COLLECTION:
                        dto.setCollect(behavior.getAdd());
                        break;
                    case COMMENT:
                        dto.setComment(behavior.getAdd());
                        break;
                    default:

                }
                return dto;
            }).reduce((agg1, agg2) -> {
                agg1.setLike(agg1.getLike() + agg2.getLike());
                agg1.setView(agg1.getView() + agg2.getView());
                agg1.setCollect(agg1.getCollect() + agg2.getCollect());
                agg1.setComment(agg1.getComment() + agg2.getComment());
                return agg1;
            });
            //判断是否包含聚合结果
            if (reduce.isPresent()) {
                aggBehaviorDTOList.add(reduce.get());
            }
        });

        return aggBehaviorDTOList;
    }

    /**
     * 获取redis list列表中的待处理行为数据
     *
     * @return
     */
    private List<NewBehaviorDTO> getRedisBehaviorList() {
        // 1.1 获取redis list中数据的长度 size
        Long size = redisTemplate.opsForList().size(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST);
        //    开启redis的管道命令
        List<Object> pipelined = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                // 开启管道执行命令
                connection.openPipeline();
                // 1.2  通过lrange方法 (0, size - 1)  获取redis列表数据
                connection.lRange(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST.getBytes(), 0, size - 1);
                // 1.3  通过ltrim方法 (size, - 1)  删除获取的redis列表数据
                connection.lTrim(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST.getBytes(), size, -1);
                return null;
            }
        }, RedisSerializer.string());

        //    统一获取管道命令  结果    List
        if (CollectionUtils.isNotEmpty(pipelined)){
            List<String> list = (List<String>) pipelined.get(0);
            return list.stream().map(str-> JSON.parseObject(str,NewBehaviorDTO.class)).collect(Collectors.toList());
        }
        return null;
    }
}